from django.conf import settings
from decimal import Decimal

from shop.models import Product
from . import forms
from coupons.models import Coupon


class Cart(object):

    """ Корзина пользователя """

    def __init__(self, request):

        self.session = request.session
        self.user_cart = self.session.get(settings.CART_SESSION_ID)
        if not self.user_cart:
            self.user_cart = self.session[settings.CART_SESSION_ID] = {}

        self.coupon_id = self.session.get('coupon_id', None)


    def clean(self):

        """ Очищаем корзину пользователя """

        del self.session[settings.CART_SESSION_ID]
        self.save()


    def save(self):

        """ Помечаем изменение сессии """

        self.session.modified = True


    def add(self, product, quantity, update_cart=False):

        """ Добавляем продукт в корзину """

        product_id = str(product.id)

        if product_id not in self.user_cart:
            self.user_cart[product_id] = {'price': str(product.price), 'quantity': 0}

        if update_cart:
            self.user_cart[product_id]['quantity'] = quantity
        else:
            self.user_cart[product_id]['quantity'] += quantity

        self.save()


    def remove(self, product):

        """ Удаляем товар из корзины пользователя """

        product_id = str(product.id)

        if product_id in self.user_cart:
            del self.user_cart[product_id]
            self.save()


    def get_total_price(self):

        """ Получаем итоговую цену корзины """

        result = sum(Decimal(item['price']) * item['quantity']
                     for item in self.user_cart.values())
        return result


    def add_update_form(self):

        """ Добавляем форму для обновления количества товаров в корзине """

        for item in self.user_cart.values():
            item['update_cart'] = forms.AddProductForm(initial={
                 'quantity': item['quantity'],
                 'update_cart': True})


    def __iter__(self):

        """ Возвращаем продукт для отображения """

        product_ids = self.user_cart.keys()
        products = Product.objects.filter(id__in=product_ids)
        user_cart = self.user_cart.copy()

        for item in user_cart:
            user_cart[item]['product'] = products.get(id=item)

        for item in user_cart.values():
            item['price'] = Decimal(item['price'])
            item['total_price'] = item['price'] * item['quantity']
            yield item


    def __len__(self):

        """ Возвращаем количество продуктов в корзине """

        result = sum(item['quantity'] for item in self.user_cart.values())
        return result


    @property
    def coupon(self):

        if self.coupon_id:
            return Coupon.objects.get(id=self.coupon_id)


    def get_discount(self):
        if self.coupon:
            return (self.coupon.discount / Decimal('100')) * self.get_total_price()

        else: return Decimal('0')


    def get_total_price_after_discount(self):

        return self.get_total_price() - self.get_discount()
